package com.ruoyi.web.controller.teacher.anomaly;

import com.ruoyi.teacher.domain.DailyPaper;
import com.ruoyi.teacher.domain.DailypaperAnomaly;
import com.ruoyi.teacher.domain.Teacher;
import com.ruoyi.teacher.mapper.DailyPaperMapper;
import com.ruoyi.teacher.mapper.DailypaperAnomalyMapper;
import com.ruoyi.teacher.mapper.TeacherMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时任务调度测试
 *
 * @author ruoyi
 */
@Component("dailyPaperTask")
public class DailyPaperTask {

    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private DailyPaperMapper dailyPaperMapper;
    @Autowired
    private DailypaperAnomalyMapper anomalyMapper;

    public void dailyPaperAnomalyReport() {

        // 获取昨日时间
        LocalDateTime yesterday = LocalDateTime.now().minusDays(1);
        // 将LocalDateTime转为Date类型
        Date date = Date.from(yesterday.atZone(ZoneId.systemDefault()).toInstant());
        // 创建一个日报异常对象
        DailypaperAnomaly anomaly = new DailypaperAnomaly();
        // 创建存储教师id和日报id的集合
        List<Long> teacherId = new ArrayList<>();
        List<Long> dailyPaperId = new ArrayList<>();
        // 获取所有教师和日报的信息
        // 遍历教师和日报，将其id加入对应的集合中
        List<Teacher> teachers = teacherMapper.selectTeacherList(new Teacher());
        for (Teacher teacher : teachers) {
            teacherId.add(teacher.getId());
        }

        List<DailyPaper> dailyPapers = dailyPaperMapper.selectDailyPaperList(new DailyPaper());
        for (DailyPaper dailyPaper : dailyPapers) {
            dailyPaperId.add(dailyPaper.getId());
        }
        // 获取未写日报的教师id
        ArrayList<Long> result = new ArrayList<>(teacherId);
        result.remove(dailyPaperId);
        // 遍历未写日报的教师id，查询是否有当日日报，若没有则添加到异常信息表中
        for (Long teacherIds : result) {
            List<DailyPaper> dailies = dailyPaperMapper.findByTeacherIds(teacherIds, date);
            if (dailies != null) {
                Teacher teas = teacherMapper.selectTeacherById(teacherIds);
                anomaly.setNote("未写日报");
                anomaly.setTeacherId(teas.getId());
                anomaly.setTime(date);
                anomalyMapper.insertDailypaperAnomaly(anomaly);
            }
        }
    }
}